//bases on Mark Nelson implementation of GST

package ru.osu.acm.system.sourcediff;

public class ST {
    private String text;
    private Uzel root;
    private int UzelsCount;

    public ST(String text) {
        UzelsCount = 0;
        this.text = text;
        root = new Uzel(this, null);

        Suf active = new Suf(root, 0, -1);
        for (int i = 0; i < text.length(); i++) {
            addPrefiks(active, i);
        }
    }

    private void addPrefiks(Suf active, int endInd) {
        Uzel lastRoditUzel = null;
        Uzel RoditUzel;

        while (true) {
            Rebro Rebro;
            RoditUzel = active.getSameUzel();

            if (active.isLR()) {
                Rebro = active.getSameUzel().findRebro(text.charAt(endInd));
                if (Rebro != null)
                    break;
            } else {
                Rebro = active.getSameUzel().findRebro(text.charAt(active.getBeginInd()));
                int Len = active.getLen();
                if (text.charAt(Rebro.getBeginInd() + Len + 1) == text.charAt(endInd))
                    break;
                RoditUzel = Rebro.rezRebro(active);
            }

            Rebro newRebro = new Rebro(endInd, text.length() - 1, RoditUzel);
            newRebro.ins();
            updSufUzel(lastRoditUzel, RoditUzel);
            lastRoditUzel = RoditUzel;

            if (active.getSameUzel() == root)
                active.incBeginInd();
            else
                active.changeSameUzel();
            active.refactor();
        }
        updSufUzel(lastRoditUzel, RoditUzel);
        active.incEndInd();
        active.refactor();
    }

    private void updSufUzel(Uzel Uzel, Uzel SufUzel) {
        if ((Uzel != null) && (Uzel != root)) {
            Uzel.setSufUzel(SufUzel);
        }
    }

    public int getNewUzelNumber() {
        return UzelsCount++;
    }


    public String getText() {
        return text;
    }

    public Uzel getRootUzel() {
        return root;
    }
}
